package com.cz.run.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.cz.run.beans.base.PageDTO;
import com.cz.run.beans.base.ReturnDTO;
import com.cz.run.beans.mysql.*;
import com.cz.run.beans.po.user.*;
import com.cz.run.beans.vo.user.*;
import com.cz.run.constants.ConstantKey;
import com.cz.run.enums.SystemCodeEnum;
import com.cz.run.service.*;
import com.cz.run.utils.DateUtil;
import com.cz.run.utils.IdcardUtil;
import com.cz.run.utils.MD5;
import com.cz.run.utils.SmsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: TODO()
 * @auther:CAIYJ
 * @Date:2018/5/25 21:53
 */
@Api(value = "用户模块")
@RestController
@RequestMapping(value = "/user")
public class UserServer {

    @Autowired
    private IUserBaseService userBaseService;

    @Autowired
    private IUserIdentityAuthService userIdentityAuthService;

    @Autowired
    private IDeliveryAddressService deliveryAddressService;

    @Autowired
    private IUserExtWechatProfileService userExtWechatProfileService;

    @Autowired
    private IUserPointService userPointService;

    @Autowired
    private IUserTradeRecordService userTradeRecordService;

    @Autowired
    private IUserReferralService iUserReferralService;

    @Autowired
    private IUserReferralDetailService userReferralDetailService;

    @Autowired
    private IUserForceCoefficientService userForceCoefficientService;

    @Autowired
    private ISmsCodeService iSmsCodeService;

    @Autowired
    private IUserForceService userForceService;

    @ApiOperation(value = "获取收货地址", notes = "获取收货地址", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "getAddress")
    public ReturnDTO<AddressVO> getAddress(HttpServletRequest request) throws Exception {
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
        EntityWrapper<DeliveryAddress> ew = new EntityWrapper<>();
        ew.where("user_id = {0}", userId);
        List<DeliveryAddress> list = deliveryAddressService.selectList(ew);
        if (null == list || list.size() == 0) {
            return ReturnDTO.fail("您未设置收货地址，请设置");
        }
        AddressVO vo = new AddressVO();
        BeanUtils.copyProperties(list.get(0), vo);
        return ReturnDTO.success(vo);
    }

    @ApiOperation(value = "修改登陆密码", notes = "修改登陆密码", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/modifyPass")
    public ReturnDTO<String> modifyPass(@RequestBody ModifyPassPO po, HttpServletRequest request) {
        if (StringUtils.isEmpty(po.getPassword())) {
            return ReturnDTO.fail(SystemCodeEnum.error_invalid_argument);
        }
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
        UserBase userBase = userBaseService.selectById(userId);
        if(null!=userBase&&0==userBase.getStatus()){
            return ReturnDTO.fail("账户被封禁，请联系客服");
        }

        if(!po.getPhone().equals(userBase.getPhone())){
            return ReturnDTO.fail("手机号不正确！请重新输入");
        }
        EntityWrapper<SmsCode> ew = new EntityWrapper<>();
        ew.where("phone = {0} ",po.getPhone()).orderBy("create_time desc limit 1");
        SmsCode smsCode =iSmsCodeService.selectOne(ew);

        if (null==smsCode||!StringUtils.equals(po.getCode(),smsCode.getCode())||smsCode.getDeadTime().getTime()<new Date().getTime()) {
            return ReturnDTO.fail("验证码不正确或已过期！请重新输入");
        }


        userBase.setPassword(MD5.GetMD5Code(po.getPassword()));
        userBaseService.updateById(userBase);
        return ReturnDTO.success("修改成功");
    }

    @ApiOperation(value = "修改交易密码", notes = "修改交易密码", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/modifyTradePass")
    public ReturnDTO<String> modifyTradePass(@RequestBody ModifyTradePassPO po, HttpServletRequest request) throws Exception {
        if (StringUtils.isBlank(po.getTradePass())) {
            return ReturnDTO.fail(SystemCodeEnum.error_invalid_argument);
        }
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
        UserBase userBase = userBaseService.selectById(userId);
        if(null!=userBase&&0==userBase.getStatus()){
            return ReturnDTO.fail("账户被封禁，请联系客服");
        }
        if(!po.getPhone().equals(userBase.getPhone())){
            return ReturnDTO.fail("手机号不正确！请重新输入");
        }
        EntityWrapper<SmsCode> ew = new EntityWrapper<>();
        ew.where("phone = {0} ",po.getPhone()).orderBy("create_time desc limit 1");
        SmsCode smsCode =iSmsCodeService.selectOne(ew);

        if (null==smsCode||!StringUtils.equals(po.getCode(),smsCode.getCode())||smsCode.getDeadTime().getTime()<new Date().getTime()) {
            return ReturnDTO.fail("验证码不正确或已过期！请重新输入");
        }

        userBase.setTradePass(MD5.GetMD5Code(po.getTradePass()));
        userBaseService.updateById(userBase);
        return ReturnDTO.success("修改成功");
    }

    @ApiOperation(value = "修改昵称", notes = "修改昵称", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/modifyNickName")
    public ReturnDTO<String> modifyNickName(@RequestBody ModifyNickNamePO po, HttpServletRequest request) throws Exception {
        if (StringUtils.isBlank(po.getNickName())) {
            return ReturnDTO.fail(SystemCodeEnum.error_invalid_argument);
        }
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
        UserBase userBase = userBaseService.selectById(userId);
        if(null!=userBase&&0==userBase.getStatus()){
            return ReturnDTO.fail("账户被封禁，请联系客服");
        }
        userBase.setNickName(po.getNickName());
        userBaseService.updateById(userBase);
        return ReturnDTO.success("修改成功");
    }

    @ApiOperation(value = "身份认证", notes = "身份认证", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "identityAuth")
    public ReturnDTO<String> identityAuth(@RequestBody IdentityAuthPO po, HttpServletRequest request) throws Exception {
        if (StringUtils.isBlank(po.getIdcard()) || StringUtils.isBlank(po.getRealName())) {
            return ReturnDTO.fail("输入不能为空");
        }
        if (!IdcardUtil.validateCard(po.getIdcard())) {
            return ReturnDTO.fail("认证失败，请校验身份证");
        }
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
        UserIdentityAuth userIdentityAuth = new UserIdentityAuth();
        userIdentityAuth.setUserId(Integer.parseInt(userId));
        userIdentityAuth.setIdcard(po.getIdcard());
        userIdentityAuth.setAddr(IdcardUtil.getProvinceByIdCard(po.getIdcard()));
        userIdentityAuth.setBirth(IdcardUtil.getBirthByIdCard(po.getIdcard()));
        userIdentityAuth.setSex(IdcardUtil.getGenderByIdCard(po.getIdcard()));
        userIdentityAuth.setRealName(po.getRealName());
        UserBase userBase = new UserBase();
        userBase.setId(Integer.parseInt(userId));
        userBase.setIdcard(po.getIdcard());
        userBase.setRealName(po.getRealName());
        userBaseService.updateById(userBase);
        try {
            userIdentityAuthService.insert(userIdentityAuth);
        } catch (DuplicateKeyException e) {
            return ReturnDTO.success("您已经完成认证！");
        }
        return ReturnDTO.success("认证成功");
    }

    @ApiOperation(value = "新增/修改收货地址", notes = "身份认证", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/uploadAddress")
    public ReturnDTO<String> uploadAddress(@RequestBody UploadAddressPO po, HttpServletRequest request) throws Exception {
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
        if (StringUtils.isEmpty(po.getPhone()) || StringUtils.isEmpty(po.getName()) || StringUtils.isEmpty(po.getAddress())) {
            return ReturnDTO.fail("输入不能为空");
        }
        EntityWrapper<DeliveryAddress> ew = new EntityWrapper<>();
        ew.where("user_id = {0}", userId);
        DeliveryAddress deliveryAddress = deliveryAddressService.selectOne(ew);
        if (deliveryAddress == null) {
            deliveryAddress = new DeliveryAddress();
            BeanUtils.copyProperties(po, deliveryAddress);
            deliveryAddress.setAddressDistrict(po.getAddressDistinct());
            deliveryAddress.setUserId(Integer.parseInt(userId));
            deliveryAddressService.insert(deliveryAddress);
        } else {
            BeanUtils.copyProperties(po, deliveryAddress, "id");
            deliveryAddressService.updateById(deliveryAddress);
        }
        return ReturnDTO.success("成功");
    }

    @ApiOperation(value = "用户信息", notes = "用户信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/info")
    public ReturnDTO<InfoVO> info(HttpServletRequest request) throws Exception {
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
        InfoVO vo = new InfoVO();
        UserBase userBase = userBaseService.selectById(userId);
        if(null!=userBase&&0==userBase.getStatus()){
            return ReturnDTO.fail("账户被封禁，请联系客服");
        }
        if (null != userBase) {
            BeanUtils.copyProperties(userBase, vo);
            vo.setIdcard(null);
            if (StringUtils.isNotEmpty(userBase.getIdcard())) {
                vo.setAuth(true);
            }
            if (StringUtils.isNotEmpty(userBase.getPassword())) {
                vo.setPass("******");
            }
            if (StringUtils.isNotEmpty(userBase.getTradePass())) {
                vo.setTradePass("******");
            }
        }
        EntityWrapper<UserExtWechatProfile> ew = new EntityWrapper<>();
        ew.where("user_id = {0}", userId);
        UserExtWechatProfile userExtWechatProfile = userExtWechatProfileService.selectOne(ew);
        if (userExtWechatProfile != null) {
            vo.setWechat(userExtWechatProfile.getNickName());
            vo.setWechatIsBinding(true);
        }
        EntityWrapper<DeliveryAddress> dew = new EntityWrapper<>();
        dew.where("user_id = {0}", userId);
        List<DeliveryAddress> list = deliveryAddressService.selectList(dew);
        if (null != list && list.size() > 0) {
            vo.setAddress(list.get(0).getAddress());
            vo.setAddressId(list.get(0).getId());
        }
        EntityWrapper<UserReferral> rew = new EntityWrapper<>();
        rew.where("user_id = {0}", userId);
        UserReferral userReferral = iUserReferralService.selectOne(rew);
        if (userReferral != null) {
            vo.setCode(userReferral.getCode());
        }
        EntityWrapper<UserPoint> ew1 = new EntityWrapper<>();
        ew1.where("user_id = {0}", userId);
        UserPoint userPoint = userPointService.selectOne(ew1);

        if (userPoint != null&&userPoint.getPoint() != null) {
            vo.setBalance(userPoint.getPoint());
        }else{
            vo.setBalance(0D);
        }
        return ReturnDTO.success(vo);
    }

    @ApiOperation(value = "积分交易记录", notes = "积分交易记录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "tradeRecords")
    public ReturnDTO<PageDTO<TradeRecordsVO>> tradeRecords(@RequestBody PageDTO po, HttpServletRequest request) throws Exception {
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
        Page<UserTradeRecord> page = new Page<>(po.getCurrentPage(), po.getPageSize());
        List<String> descs = new ArrayList<>();
        descs.add("trade_time");
        page.setDescs(descs);
        EntityWrapper<UserTradeRecord> rew = new EntityWrapper<>();
        rew.where("user_id = {0}", userId);
        page = userTradeRecordService.selectPage(page, rew);
        if (null != page && null != page.getRecords() && page.getRecords().size() > 0) {
            List<TradeRecordsVO> list = new ArrayList<>();
            TradeRecordsVO vo = null;
            for (UserTradeRecord userTradeRecord : page.getRecords()) {
                vo = new TradeRecordsVO();
                BeanUtils.copyProperties(userTradeRecord, vo);
                if (null != userTradeRecord.getTradeTime()) {
                    vo.setTradeTimeStr(DateUtil.currentTimeMillisCN1(userTradeRecord.getTradeTime()));
                }
                list.add(vo);
            }
            po.setContent(list);
        }
        po.setTotalRecord(page.getTotal());
        return ReturnDTO.success(po);
    }

    @ApiOperation(value = "我的积分", notes = "我的积分", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "point")
    public ReturnDTO<PointVO> point(HttpServletRequest request) throws Exception {
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
        EntityWrapper<UserPoint> ew = new EntityWrapper<>();
        ew.where("user_id = {0}", userId);
        PointVO vo = new PointVO();
        UserPoint userPoint = userPointService.selectOne(ew);
        if (userPoint != null) {
            BeanUtils.copyProperties(userPoint, vo);
            vo.setPoint(userPoint.getPoint());
            if (userPoint.getPoint() == null) {
                vo.setPoint(0D);
            }
        }
        return ReturnDTO.success(vo);
    }

    @ApiOperation(value = "新注册用户填写上家推广码", notes = "新注册用户填写上家推广码", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/fillCode")
    public ReturnDTO<String> fillCode(@RequestBody FillCodePO po, HttpServletRequest request) throws Exception {
        if (StringUtils.isEmpty(po.getCode())) {
            return ReturnDTO.fail("邀请码为空，请重新输入");
        }
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
        EntityWrapper<UserReferralDetail> ewu = new EntityWrapper<>();
        ewu.where("referral1_uid = {0}", userId);
        UserReferralDetail userReferralDetail = userReferralDetailService.selectOne(ewu);
        if (userReferralDetail != null) {
            return ReturnDTO.fail("您已经使用过受邀权限！");
        }
        EntityWrapper<UserReferral> ew = new EntityWrapper<>();
        ew.where("`code` = {0}", po.getCode());
        UserReferral userReferral = iUserReferralService.selectOne(ew);
        if (userReferral == null) {
            return ReturnDTO.fail("无该该邀请码用户，请确认后再输入");
        }
        UserReferralDetail detail = new UserReferralDetail();
        detail.setReferral1Uid(userReferral.getUserId());
        detail.setUserId(Integer.parseInt(userId));
        detail.setRegistDate(userReferral.getCreateTime());
        userReferralDetailService.insert(detail);
        return ReturnDTO.success("成功");
    }

    @ApiOperation(value = "我的邀请记录", notes = "我的邀请记录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/invitationRecord")
    public ReturnDTO<PageDTO<InvitationRecordVO>> invitationRecord(HttpServletRequest request, @RequestBody PageDTO po) throws Exception {
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
        Page<UserReferralDetail> page = new Page<>(po.getCurrentPage(), po.getPageSize());
        EntityWrapper<UserReferralDetail> ew = new EntityWrapper<>();
        ew.where("referral1_uid = {0}", userId);
        ew.orderBy("regist_date", false);
        page = userReferralDetailService.selectPage(page, ew);
        PageDTO<InvitationRecordVO> pageDTO = new PageDTO<>();
        if (null != page && page.getRecords() != null && page.getRecords().size() > 0) {
            List<InvitationRecordVO> list = new ArrayList<>();
            UserBase userBase = null;
            InvitationRecordVO vo = null;
            for (UserReferralDetail detail : page.getRecords()) {
                vo = new InvitationRecordVO();
                userBase = userBaseService.selectById(detail.getUserId());
                if (userBase != null) {
                    vo.setName(userBase.getPhone());
                }
                if (detail.getRegistDate() != null) {
                    vo.setTime(DateUtil.currentTimeMillisCN1(detail.getRegistDate()));
                }
                list.add(vo);
            }
            pageDTO.setContent(list);
            pageDTO.setTotalRecord(page.getTotal());
        }
        return ReturnDTO.success(pageDTO);
    }

    @ApiOperation(value = "发送短信验证码", notes = "发送短信验证码", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/sendCode")
    public ReturnDTO<String> sendCode(@RequestBody SendCodePO po) throws Exception {
        String code =SmsUtil.getCode(6);
        SmsUtil.sendMsg(code,po.getPhone());

        SmsCode smsCode = new SmsCode();
        smsCode.setCode(code);
        smsCode.setPhone(po.getPhone());
        smsCode.setDeadTime(new Date(new Date().getTime()+5000));
       iSmsCodeService.insert(smsCode);
        return ReturnDTO.success("成功");
    }
}
